package com.huniu.analysis.hive.assistant;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.BlockingQueue;

public class NectarProducerImpl implements INectarProducer {

	private File[] dictionaryFiles;

	private BlockingQueue<String[]> dicQueue;

	public void setDictionaryFiles(File[] dictionaryFiles) {
		this.dictionaryFiles = dictionaryFiles;
	}

	public NectarProducerImpl(BlockingQueue<String[]> dicQueue) {
		this.dicQueue = dicQueue;
	}

	private void clearNectarArray(String[] nectarArray) {
		if (nectarArray != null) {
			for (int i = 0; i < nectarArray.length; i++) {
				nectarArray[i] = null;
			}
		}
	}

	private void produceDictionaries() throws IOException {
		try {
			String[] nectarArray = new String[NECTAR_FACTOR_ONCE_UPPER_LIMIT];
			int index = 0;
			for (File file : dictionaryFiles) {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(new FileInputStream(file)));
				String line = null;
				while ((line = reader.readLine()) != null) {
					String[] array = line.split("\\s");
					for (String item : array) {
						if ( ! item.matches("\\s") && ! item.equals("") ) {
							if (index >= NECTAR_FACTOR_ONCE_UPPER_LIMIT) {
								addOnceUpperLimitToQueue(nectarArray,NECTAR_FACTOR_ONCE_UPPER_LIMIT);
								index = 0;
								clearNectarArray(nectarArray);
							}
							nectarArray[index++] = item;
						}
					}
				}
			}
			if (index != 0) {
				addOnceUpperLimitToQueue(nectarArray,index);
				index = 0;
				clearNectarArray(nectarArray);
			}
		} catch (InterruptedException e) {

		}
	}

	private void addOnceUpperLimitToQueue(String[] array, int length)
			throws InterruptedException {
		String[] arrayCopy = new String[length];
		System.arraycopy(array, 0, arrayCopy, 0, length);
		dicQueue.put(arrayCopy);
	}

	public void produce() {
		try {
			produceDictionaries();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		produce();
	}
}
